﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HotellApplikationASP.Models;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;

namespace HotellApplikationASP
{
    public partial class BookingStart : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["ERRORMESSAGE"] != null)
            {
                error.Text = Session["ERRORMESSAGE"].ToString();
            }
        }

        protected void cmdSave_Click(object sender, EventArgs e)
        {
            var sDate = DateTime.Parse(datepickerFrom.Text);
            var eDate = DateTime.Parse(datepickerTo.Text);

            var db = new HotellbokningASPEntities();
            var unavailableRooms = db.RoomOrderDetails.Where(p => p.StartDate >= sDate && p.EndDate <= eDate);
            var allRooms = db.Rooms.Select(p => p.Id).ToList();
            var costForRoom = db.RoomTypes.Where(p => p.Description == DDLRoomType.SelectedItem.Text).FirstOrDefault();

            foreach (RoomOrderDetail room in unavailableRooms)
            {
                allRooms.RemoveAll(p => p == room.RoomId);
            }

            if (allRooms.Count <= 0)
            {
                Session["ERRORMESSAGE"] = "No available rooms";
                return;
            }

            var createRoomID = allRooms.FirstOrDefault();
            var totalCost = Convert.ToInt32(costForRoom.CostPerNight * (eDate - sDate).TotalDays);
            var userID = User.Identity.GetUserId();
            

            var order = new Order()
            {
                OrderDate = DateTime.Today,
                Total = totalCost,
                IsPayed = false,
                CustomId = userID
 
            };

            db.Orders.Add(order);

            var orderDetail = new RoomOrderDetail()
            {
                StartDate = sDate,
                EndDate = eDate,
                RoomId = createRoomID,
                OrderId = order.Id,
                Total = totalCost
            };

            Session["orderDetails"] = orderDetail;
            db.RoomOrderDetails.Add(orderDetail);
            db.SaveChanges();

            var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
            ApplicationUser user = manager.FindById(userID);
            var mail = new MailClient();
            mail.MyMail(user.Email, "New booking", "Thank you for your booking no. " + order.Id.ToString());

            Server.Transfer("/BookingConfirmation.aspx");
        }

    }
}